package org.softmed.neodatis.persistence.impl;

import java.io.File;
import java.util.Date;
import org.softmed.filehandling.FileUtil;
import org.softmed.rest.generation.scafold.AppConfig;
import org.softmed.rest.generation.solution.PersistenceFactory;

public class NeoDatisPersistenceFactory implements PersistenceFactory {

	FileUtil util = new FileUtil();

	@Override
	public void createPersistenceSolution(AppConfig app) throws Throwable {
		String dbFileName = "database.odb";
		String name = app.getName();
		String script = "import org.neodatis.odb.ODBServer;\n"
				+ "import org.softmed.neodatis.persistence.impl.ODBPersistenceProvider;\n"
				+ "import org.softmed.neodatis.util.id.GenerateIDConfigurator;\n"
				+ "import org.softmed.neodatis.util.id.generator.*;\n"
				+ "import org.softmed.neodatis.util.provider.*;\n"
				+ "import org.softmed.neodatis.util.trigger.TriggerEnvironment;\n\n"
				+ "String ODBFileName = \""
				+ dbFileName
				+ "\";\n"
				+ "String ODBName = \""
				+ name
				+ "\";\n\n"
				+ "server = ClientServerProviderManager.getDefaultServer();\n"
				// + "server.startupServer();\n"
				+ "server.registerODB(ODBName, app.path+\"/\"+ODBFileName);\n"
				+ "ClientServerProvider csProvider = new ClientServerProvider(server,ODBName);\n\n"
				+ "GenerateIDConfigurator generateFieldConfig = new GenerateIDConfigurator(csProvider);\n"
				+ "TriggerEnvironment tenv = new TriggerEnvironment();\n"
				+ "tenv.getInserts().add(generateFieldConfig.getGenerateIDTrigger());\n"
				+ "server.registerTriggerEnvironments(ODBName, tenv);\n\n"
				+ "provider = new ODBPersistenceProvider(csProvider);\n"
				+ "name = \"" + name + "-provider\";";

		util.saveToFile(new File(app.getPath() + "\\" + "persistence.groovy"),
				script);
	}
}
